package com.bolt.admin.module.sys.controller;

import com.bolt.admin.module.sys.entity.AreaEntity;
import com.bolt.admin.module.sys.service.AreaService;
import com.bolt.common.collection.CollectionUtil;
import com.bolt.common.utils.StrUtil;
import com.bolt.convention.data.ResultMessage;
import com.bolt.convention.data.Results;
import com.bolt.support.ui.tree.helper.TreeRenderHelper;
import com.bolt.support.ui.tree.vo.UITreeNode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Api(tags = "地区信息")
@RestController
@RequestMapping("/api/sys/area")
@RequiredArgsConstructor
public class AreaController {

    private final AreaService areaService;

    @ApiOperation("地区信息:分级获取地区数据")
    @GetMapping(value = "/getTree")
    public ResultMessage<List <UITreeNode>> getTree(@RequestParam(name = "pid", required = false) Long id, @RequestParam Map <String, String> params) {
        boolean loadAllNodes = StrUtil.isEmpty(params.get("loadAllNodes")) ? false : Boolean.parseBoolean(params.get("loadAllNodes"));
        List <UITreeNode> dataArray = new ArrayList <>();
        TreeRenderHelper.buildNodesTreeView(areaService, id, params, dataArray, loadAllNodes);
        return Results.success(dataArray);
    }

    @ApiOperation("地区信息:根据ID获取同级与上级数据")
    @PostMapping("/findAll")
    public ResultMessage<List <UITreeNode>> findALl(@RequestBody List <String> areaCode) {
        List <AreaEntity> areaEntities = areaService.findByAreaCode(areaCode);
        List <Long> ids = areaEntities.stream().map(AreaEntity::getId).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(ids)) {
            List <AreaEntity> areas = areaService.findAll(ids);
            return  Results.success(areaService.buildTree(areas));
        }
        return Results.success(areaService.buildTree(areaService.findRoot()));
    }


}

 